package com.example.mediamoudle.thumb

import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.android.baselibrary.base.BaseAdapter
import com.bumptech.glide.Glide
import com.example.mediamoudle.R
import com.example.mediamoudle.databinding.ItemVideoFrameBinding


/**
 * 帧列表 adapter
 * @author SamWang(33691286@qq.com)
 * @date 2019-07-19
 */
class VideoFrameAdapter(private val frameWidth: Int) : BaseAdapter<VideoFrameData,ItemVideoFrameBinding>() {




    override fun getItemLayoutId(): Int = R.layout.item_video_frame

    override fun covert(binding: ItemVideoFrameBinding, item: VideoFrameData, position: Int) {
        Log.i("TAG145", "1convert:index:${position} isLast:${item.isLastItem} ,time:${item.time},isFirst:${item.isFirstItem} ,frameWidth:$frameWidth")

        val imageView = binding.iv
        val layoutParams = binding.root.layoutParams
        layoutParams.width = item.frameWidth

        binding.mask.setCornerRadiusDp(4f)
        binding.mask.setCorners(item.isFirstItem, item.isLastItem, item.isFirstItem, item.isLastItem)
        val maskLayoutParams =  binding.mask.layoutParams as FrameLayout.LayoutParams
        val ivLayoutParams = imageView.layoutParams as FrameLayout.LayoutParams

        if (item.isFirstItem) {
            maskLayoutParams.gravity = Gravity.LEFT
            ivLayoutParams.gravity = Gravity.RIGHT
        } else {
            maskLayoutParams.gravity = Gravity.RIGHT
            ivLayoutParams.gravity = Gravity.LEFT
        }

        maskLayoutParams.width = if (item.isFirstItem && item.isLastItem) {
            ivLayoutParams.gravity = Gravity.LEFT
            ivLayoutParams.marginStart = -item.offsetX //只有一帧考虑位移

            item.frameWidth             //如果一段视频在列表中只有一帧，则要显示全部圆角，遮罩同步缩小
        } else {
            ivLayoutParams.marginStart = 0
            frameWidth
        }

        imageView.tag = position

        Glide.with(imageView)
            .asBitmap()
            .load(item.videoData.originalFilePath)
            .frame(item.frameClipTime * 1000)
            .thumbnail(
                //todo 更好的方案是往前找一个已经有的缓存帧
                Glide.with(imageView).asBitmap().load(item.videoData.originalFilePath)
            )
            .into(imageView)
    }
}




